package com.demo.personalaccountingbackend.service.impl;

import com.demo.personalaccountingbackend.data.MyUserDetails;
import com.demo.personalaccountingbackend.entity.User;
import com.demo.personalaccountingbackend.mapper.UserMapper;
import com.demo.personalaccountingbackend.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 类描述信息
 *
 * @author zgx
 * @version 1.0
 * @date 2025/10/24 14:53
 */
@Service
@RequiredArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {

            User user = userMapper.findByUsername(username);

            if (user == null) {
                throw new UsernameNotFoundException("用户不存在: " + username);
            }

            // 检查用户状态
            if (user.getStatus() != null && user.getStatus() != 0) {
                throw new UsernameNotFoundException("用户已被禁用: " + username);
            }
            // 创建自定义的UserDetails对象
            return new MyUserDetails(user);

        } catch (Exception e) {
            if (e instanceof UsernameNotFoundException) {
                throw e;
            }
            throw new UsernameNotFoundException("查询用户信息失败: " + username, e);
        }
    }
}
